import React, { useState } from 'react';
import { Form, Input, Button, message, Spin } from 'antd';
import { useNavigate } from 'react-router-dom';
import { loginStore } from '../../../store/public/loginStore';
import { login } from '../../../apis/public/user';
import styles from './Login.module.css';
import { systemName } from '../../../globals/system.tsx';

interface LoginFormValues {
  username: string;
  password: string;
}

const Login: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);

  const onFinish = async (values: LoginFormValues) => {
    try {
      setLoading(true);
      // 使用 AES 加密密码
      const encryptedPassword = window.btoa(values.password);
      const response = await login(values.username, encryptedPassword);
      const data = response.data;
      if (data && data.token) {
        // 更新登录状态并缓存信息
        loginStore.login(data.token, data.userInfo);
        message.success('登录成功');
        navigate('/app');
      } else {
        message.error('登录失败：未获取到有效token');
      }
    } catch (error) {
      console.error('登录失败:', error);
      //message.error('登录失败，请检查用户名和密码');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className={styles.loginContainer}>
      <div className={styles.loginBox}>
        <h2 className={styles.loginTitle}>{systemName}</h2>
        <Spin spinning={loading}>
          <Form
            name="login"
            className={styles.loginForm}
            initialValues={{ remember: true }}
            onFinish={onFinish}
            size="large"
          >
            <Form.Item
              name="username"
              rules={[{ required: true, message: '请输入用户名!' }]}
            >
              <Input placeholder="用户名" />
            </Form.Item>

            <Form.Item
              name="password"
              rules={[{ required: true, message: '请输入密码!' }]}
            >
              <Input.Password placeholder="密码" />
            </Form.Item>

            <Form.Item>
              <Button 
                type="primary" 
                htmlType="submit" 
                className={styles.loginButton}
                loading={loading}
              >
                登录
              </Button>
            </Form.Item>
          </Form>
        </Spin>
      </div>
    </div>
  );
};

export default Login; 